package com.example.demo.OtherCoding;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-05-13
 * Time: 14:21
 */
public class Code_trimBST {
    class Solution {
        //二叉搜索树!!!
        public TreeNode trimBST(TreeNode root, int low, int high) {
            if (root == null) {
                return null;
            }
            root.left = trimBST(root.left, low, high);
            root.right = trimBST(root.right, low, high);
            //该节点应该被修剪
            if (root.val > high || root.val < low) {
                TreeNode cur = root.right;
                if (cur != null) {
                    //找到右树的最左
                    while (cur.left != null) {
                        cur = cur.left;
                    }
                    cur.left = root.left;
                    return root.right;
                } else {
                    return root.left;
                }
            }
            return root;
        }
    }
}